package movee.manager.rsync;

import movee.config.AppProperties;
import movee.os.FileSystemService;
import lombok.extern.slf4j.Slf4j;
import movee.os.SafeExec;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.stereotype.Service;

/**
 * rsync客户端
 *
 * @author movee
 */
@Service
@Slf4j
public class RsyncClient {

    private final AppProperties appProperties;
    private final FileSystemService fileSystemService;

    public RsyncClient(AppProperties appProperties, FileSystemService fileSystemService) {
        this.appProperties = appProperties;
        this.fileSystemService = fileSystemService;
    }

    public void syncToRemoteDaemon(String host, String src, String dst) {

        /**
         * src: /backup-cfgs/latest/2023-03-25/bjyz
         * dst: 2023-03-25/
         */

        try {
            String secretFile = appProperties.getRsyncSecretFileName();
            String[][] cmdArray = {
                    {"/bin/sh"},
                    {"-c"},
                    {"rsync -zrtopgu --bwlimit=1000 --progress --password-file=%s %s backup@%s::backup/%s",
                            secretFile, src, host, dst}
            };

            Process process = SafeExec.execute(cmdArray);
            String echo = fileSystemService.readInputStream(process.getInputStream());
            log.debug("=====syncToRemoteDaemon echo: {}", echo);
            // ProcessBuilder processBuilder = new ProcessBuilder("mv", "-f", srcDir, dstDir);
            // Process process = processBuilder.start();
            process.waitFor();

        }  catch (Throwable t) {
            log.error("syncToRemoteDaemon failed. host: {}, src: {}, dst: {}, stack: {}",
                    host, src, dst, ExceptionUtils.getStackTrace(t));
        }
    }

}
